💡 AI 인사이트

🤖 AI가 여기에 결과를 출력합니다...

댓글 커뮤니티

쿠팡이벤트

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

검색

    로딩 중이에요... 🐣

    [코담] 웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트

    23 정적 콘텐츠 | ✅ 저자: 이유정(박사)

    정적 파일(static files)이란 이미지, CSS, JavaScript, 텍스트, 문서 등 서버에서 고정된 형태로 제공되는 파일들을 말합니다. 사용자의 요청에 따라 내용이 바뀌지 않고 항상 동일한 파일을 그대로 전달하는 것이 특징입니다.

    FastAPI에서 Static Files 사용하는 방법

    📁 디렉토리 구조

    project/
    │
    ├── static/
    │   ├── styles/
    │   │   └── styles.css
    │   ├── scripts/
    │   │   └── index.js
    │   ├── images/
    │   │   └── logo.png
    │   └── sample.txt
    └── main.py
    

    예제 코드 main.py

    from fastapi import FastAPI, Request
    from fastapi.responses import HTMLResponse
    from fastapi.templating import Jinja2Templates
    from fastapi.staticfiles import StaticFiles
    
    app = FastAPI()
    
    # 정적파일 제공 설정 (CSS, JS 등)
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    # 템플릿 디렉토리 설정
    templates = Jinja2Templates(directory="templates")
    
    # HTML 페이지 렌더링
    @app.get("/", response_class=HTMLResponse)
    async def read_index(request: Request):
        return templates.TemplateResponse("index.html", {"request": request, "title": "FastAPI HTML 페이지"})
    

    static/index.html

    <!DOCTYPE html>
    <html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>{{ title }}</title>
        <!-- 스타일 연결 -->
        <link rel="stylesheet" href="/static/styles/styles.css">
        <!-- 자바스크립트 연결 -->
        <script src="/static/scripts/index.js" defer></script>
    </head>
    <body>
        <h1>{{ title }}</h1>
        <p>FastAPI에서도 HTML을 렌더링할 수 있어요!</p>
    
        <!-- 이미지도 출력해볼게요 -->
        <img src="/static/images/logo.png" alt="로고 이미지" width="200">
    </body>
    </html>
    

    static/styles/styles.css

    body {
        background-color: lightblue;
        color: navy;
        font-family: sans-serif;
    }
    

    static/scripts/index.js

    alert("Hello from FastAPI static JS!");
    

    static/sample.txt

    This is a sample static text file.
    

    static/images/logo.png 이 경로에 로고파일을 저장합니다.

    실행하고 결과 확인

    uvicorn main:app --reload
    

    결과 확인

    • alert() 팝업이 뜨고
    • 배경이 연한 파란색이고
    • 로고 이미지가 표시되며
    • 제목과 문구가 잘 렌더링된 HTML 페이지가 나타납니다.
    TOP
    preload preload